package com.example.blue;

import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import java.util.concurrent.ConcurrentLinkedQueue;


public class JiaozhunActivity extends AppCompatActivity implements DataProcessorManager.DataUpdateListener{
    private static final String TAG = "JiaozhunActivity";
    private BluetoothService bluetoothService;
    private boolean isBound = false;
    private Button btn;
    private DataProcessorManager processorManager;
    private String deviceId;
    private LinearLayout loadingOverlay ;
    private ConcurrentLinkedQueue<byte[]> dataQueue = new ConcurrentLinkedQueue<>();


    private final ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {
            BluetoothService.LocalBinder binder = (BluetoothService.LocalBinder) service;
            bluetoothService = binder.getService();
            isBound = true;
            Log.d("ServiceTest", "onServiceConnected: bound=" + isBound);
            dataQueue  = bluetoothService.getDataQueue();
//            if(dataQueue.isEmpty()){
//                new AlertDialog.Builder(JiaozhunActivity.this)
//                        .setTitle("提示")
//                        .setMessage("未收到数据，请重试")
//                        .setPositiveButton("确定", (dialog, which) -> {
//                            finish();
//                        })
//                        .show();
//            }else {
                processorManager = DataProcessorManager.getInstance(dataQueue);
//            }
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            isBound = false;
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jiaozhun);
        SharedPreferences sp = getSharedPreferences("my_cache", Context.MODE_PRIVATE);
        deviceId = sp.getString("deviceId", "");
        System.out.println(deviceId);
        if (deviceId == "" || deviceId.isEmpty()) {
            Toast.makeText(JiaozhunActivity.this,"未获取到蓝牙MAC地址，请重新连接",Toast.LENGTH_SHORT).show();
        }
        // 开启返回箭头
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeAsUpIndicator(null);
        getSupportActionBar().setTitle("校准动作");
        loadingOverlay  = findViewById(R.id.loadingOverlay);

        btn = findViewById(R.id.jiaozhunBtn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(JiaozhunActivity.this);
                builder.setTitle("请选择")
                        .setItems(new String[]{"左手", "右手"}, (dialog, which) -> {
                            if (which == 0) {
                                SharedPreferences sp = getSharedPreferences("my_cache", MODE_PRIVATE);
                                SharedPreferences.Editor editor = sp.edit();
                                editor.putInt("handDir", 1);
                                editor.apply();

                                loadingOverlay.setVisibility(View.VISIBLE);
                                processorManager.setDataUpdateListener(JiaozhunActivity.this);
                                processorManager.startProcessing();
                                processorManager.setProcessingFunction(ProcessingFunction.DuizhiBias);
                            } else {
                                SharedPreferences sp = getSharedPreferences("my_cache", MODE_PRIVATE);
                                SharedPreferences.Editor editor = sp.edit();
                                editor.putInt("handDir", 2);
                                editor.apply();
                                loadingOverlay.setVisibility(View.VISIBLE);
                                processorManager.setDataUpdateListener(JiaozhunActivity.this);
                                processorManager.startProcessing();
                                processorManager.setProcessingFunction(ProcessingFunction.DuizhiBias);
                            }
                        })
                        .setNegativeButton("取消", null)
                        .show();
                Toast.makeText(JiaozhunActivity.this, "开始测试", Toast.LENGTH_SHORT).show();

            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        Intent intent = new Intent(this, BluetoothService.class);
        intent.putExtra("DEVICE_ADDRESS", deviceId); // 如果需要
        bindService(intent, connection, Context.BIND_AUTO_CREATE);
    }
    public void onDataProcessed(ProcessedData data) {
        String flag = data.getFlag();
        System.out.println("jiaozhun-Flag:" + flag);
        if(flag.equals("duizhibias")){
            SharedPreferences sp = getSharedPreferences("my_cache", MODE_PRIVATE);
            SharedPreferences.Editor editor = sp.edit();
            editor.putBoolean("isJiaozhun", true);
            editor.apply();
            loadingOverlay.setVisibility(View.GONE);
            Toast.makeText(JiaozhunActivity.this,"校准完成",Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    // 处理返回箭头点击事件
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish(); // 结束当前Activity，返回上一个
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}